import api from "./../../../common/api"
import {
  mathchSearchValue,
  _debounce
} from './../../../utils/utilsNew';
import * as transferData from './../../../models/transferData'

const STORAGE_FRONT = 'search_history_'

Page({
  /**
   * 页面的初始数据
   */
  data: {
    currentCity: '',
    placeholder: '', // 输入提示
    searchTextValue: '',
    historyList: [],
    searchList: [],
    pageIndex: 1,
    pageSize: 10,
    loading: false,
    history: '', // 区分不同页面来源隔离历史数据
    isShowHistory: false,
    accurate: '', // 区分不同页面来源调用不同小区接口
    isAccurate: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let t = this
    t.initData(options)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  initData(options) {
    let t = this
    t.setData({
      currentCity: options.city || '',
      placeholder: options.placeholder || '',
      history: options.history || '',
      isShowHistory: options.history ? true : false,
      accurate: options.accurate || '',
      isAccurate: options.accurate ? true : false,
    })

    if (options.search) {
      t.setData({
        searchTextValue: options.search
      })
      t.data.isAccurate && t.loadSearchList(t.data.searchTextValue)
    }

    if (t.data.isShowHistory) {
      let historyList = wx.getStorageSync(`${STORAGE_FRONT}${t.data.history}`)
      if (historyList) {
        t.setData({
          historyList
        })
      }
    }

  },

  onInputChange: _debounce(function (e) {
    let t = this
    let keyword = e.detail.value || ''
    t.setData({
      searchTextValue: keyword,
    })
    if (t.data.isAccurate) {
      t.setData({
        loading: true
      })
      t.loadSearchList(keyword)
        .then(() => {
          t.setData({
            loading: false,
          })
        })
    }
  }, 500),

  loadSearchList(keyword) {
    let t = this
    return new Promise((resolve, reject) => {
      if (!keyword) {
        t.setData({
          searchList: [],
        })
        resolve()
        return
      }
      let {
        pageIndex,
        pageSize,
        accurate,
        currentCity,
      } = t.data
      api[accurate]({
        city: currentCity,
        resblockName: keyword,
        page: pageIndex,
        pageSize,
      }, res => {
        if (res && res.data && res.data.isSuccess && res.data.content) {
          let result = res.data.content.rows || []
          let formatList = result.map(item => {
            return {
              contentList: mathchSearchValue(item.resblockName, keyword),
              id: item.resblockId,
              keyword: item.resblockName || '',
              saleTotal: item.saleTotal || 0,
              rentTotal: item.rentTotal || 0,
            }
          })
          t.setData({
            searchList: formatList,
          })
          resolve()
        } else {
          resolve()
        }
      })
    })
  },

  onClickSearch(e) {
    let t = this
    let key = e.currentTarget.dataset.key
    t.data.searchList.forEach(item => {
      if (item.keyword === key) {
        t.jumpToList({
          type: 'key',
          value: item.keyword,
          label: item.keyword,
        })
      }
    })
  },

  onSearchConfirm(e) {
    let t = this
    let keyword = e.detail.value
    if (!(keyword && keyword.trim())) {
      return wx.showToast({
        title: '请输入搜索词',
        icon: 'none',
      })
    }
    t.jumpToList({
      type: 'key',
      value: keyword,
      label: keyword,
    })
  },

  onSearchConfirmByBtn() {
    let t = this
    let keyword = t.data.searchTextValue
    if (!(keyword && keyword.trim())) {
      return wx.showToast({
        title: '请输入搜索词',
        icon: 'none',
      })
    }
    t.jumpToList({
      type: 'key',
      value: keyword,
      label: keyword,
    })
  },

  onClickHistory(e) {
    let t = this
    let currentIndex = e.target.dataset.index
    t.data.historyList.forEach((item, index) => {
      if (index === currentIndex) {
        t.jumpToList(item)
      }
    })
  },

  jumpToList({
    type,
    value,
    label,
  }) {
    let t = this
    let {
      historyList,
      accurate
    } = t.data
    transferData.setData('cooperativeSearch', {
      type,
      label,
      value,
    })
    if (t.data.isShowHistory) {
      let repetitiveIndex = -1
      historyList.forEach((item, index) => {
        if (item.value === value) {
          repetitiveIndex = index
        }
      })
      if (repetitiveIndex >= 0) {
        historyList.splice(repetitiveIndex, 1)
      }
      historyList.push({
        type,
        value,
        label,
      })
      let newHistoryList = historyList.slice(0, 20)
      wx.setStorageSync(`${STORAGE_FRONT}${this.data.history}`, newHistoryList)
      if (accurate === 'likeHouseCooperationByName') {
        t.addCooperationSearchLog(label)
      }
    }
    wx.navigateBack()
  },

  onSearchClear() {
    this.setData({
      loading: false,
    }, () => {
      this.setData({
        searchTextValue: '',
      })
    })
  },

  onHistoryClear() {
    let t = this
    wx.showModal({
        content: "确认清空历史搜索记录？",
      })
      .then((res) => {
        if (res.confirm) {
          t.setData({
            historyList: []
          })
          wx.removeStorageSync(`${STORAGE_FRONT}${t.data.history}`)
        }
      })
  },

  addCooperationSearchLog(keyword) {
    api.addCooperationSearchLog({
      searchWord: keyword
    }, () => {

    })
  }
})